<?php

namespace app\admin\controller\subject;

use app\common\controller\Backend;

// use traits\model\SoftDelete;

/**
 * 课程控制器
 */
class Subject extends Backend
{
    // use SoftDelete;

    // protected $deleTime = 'deletetime';

    protected $model = null;

    // 关联查询
    protected $relationSearch = true;

    // 初始化
    public function _initialize()
    {
        parent::_initialize();

        $this->model = model('Subject.Subject');
        $this->CategoryModel = model('Subject.Category');
        $this->ChapterModel = model('Subject.Chapter');
        $this->TeacherModel = model('Teacher.Teacher');

    }

    // 首页
    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);

        if ($this->request->isAjax())
        {
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->with(['category','teacher'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->count();

            $list = $this->model
                ->with(['category','teacher'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }

        return $this->view->fetch();
    }

    //添加
    public function add()
    {
        if($this->request->isPost())
        {
            //接收row前缀的数据，并接收为数组类型
            $params = $this->request->param('row/a');

            //组装数据
            $data = [
                'title' => $params['title'],
                'price' => $params['price'],
                'content' => $params['content'],
                'thumbs' => $params['thumbs'],
                'cateid' => $params['cateid'],
            ];

            //插入到数据库中
            $result = $this->model->validate('common/Subject/Subject')->save($data);

            if($result === FALSE)
            {
                $this->error($this->model->getError());
                exit;
            }else
            {
                $this->success('添加课程成功');
                exit;
            }

        }

        //先将课程分类查询出来
        $catelist = $this->CategoryModel->column('id,name');
        $this->assign('catelist', build_select('row[cateid]', $catelist, [], ['class'=>'selectpicker', 'required'=>'']));

        return $this->view->fetch();
    }

    // 编辑
    public function edit($ids = NULL)
    {
        //根据id要判断数据是否存在
        $row = $this->model->find($ids);

        //数据丢失，记录不存在
        if(!$row)
        {
            $this->error(__('No Results were found'));
            exit;
        }

        //判断是否有post过来请求
        if($this->request->isPost())
        {
            //接收row前缀请求参数，并返回一个数组类型
            $params = $this->request->param('row/a');

            //组装数据
            $data = [
                'id' => $ids,
                'title' => $params['title'],
                'content' => $params['content'],
                'price' => $params['price'],
                'cateid' => $params['cateid'],
                'thumbs' => $params['thumbs'],
            ];

            //直接去更新
            $result = $this->model->validate('common/Subject/Subject')->isUpdate(true)->save($data);

            if($result === FALSE)
            {
                $this->error($this->model->getError());
                exit;
            }

            //判断是否有上传新图片
            if($data['thumbs'] != $row['thumbs'])
            {
                //不相等就说明有换图片了，就删除掉旧图片
                @is_file(".".$row['thumbs']) && @unlink(".".$row['thumbs']);
            }

            $this->success('编辑课程成功');
            exit;
        }

        //先将课程分类查询出来
        $catelist = $this->CategoryModel->column('id,name');
        $this->assign('catelist', build_select('row[cateid]', $catelist, $row['cateid'], ['class'=>'selectpicker', 'required'=>'']));

        // 有数据要赋值到模板中去
        $this->assign('row', $row);

        //模板渲染
        return $this->view->fetch();
    }

    //软删除
    public function del($ids = NULL)
    {
        $list = $this->model->select($ids);

        //没有数据
        if(!$list)
        {
            $this->error(__('No Results were found'));
            exit;
        }

        //软删除
        $result = $this->model->destroy($ids);

        if($result === FALSE)
        {
            $this->error('删除失败');
            exit;
        }else
        {
            $this->success('删除成功');
            exit;
        }
    }

    // 回收站
    public function recyclebin()
    {
        $this->request->filter(['strip_tags', 'trim']);

        if ($this->request->isAjax())
        {
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->onlyTrashed()
                ->with(['category'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->count();

            $list = $this->model
                ->onlyTrashed()
                ->with(['category'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }

    }

    // 还原
    public function restore($ids = null)
    {
        $list = $this->model->onlyTrashed()->select($ids);

        if(!$list)
        {
            $this->error('课程不存在');
            exit;
        }

        $result = $this->model->onlyTrashed()->where(['id' => ['IN',$ids]])->update(['deletetime' => null]);

        if($result === FALSE)
        {
            $this->error('还原失败');
            exit;
        }else
        {
            $this->success('还原成功');
            exit;
        }
    }

    // 真实删除
    public function destroy($ids = null)
    {
        $list = $this->model->onlyTrashed()->select($ids);

        if(!$list)
        {
            $this->error('课程不存在');
            exit;
        }

        // 获取选中课程里的章节数据
        $chapter = $this->ChapterModel->where(['subid' => ['IN',$ids]])->select();

        // 删除选中课程数据
        $SubjectStatus = $this->model->destroy($ids,true);

        if($SubjectStatus === FALSE)
        {
            $this->error('删除课程失败');
            exit;
        }else
        {
            $video = array_column($chapter, "url");
            $video = array_filter($video);
            $video = array_unique($video);

            $thumbs = array_column($list, "thumbs");
            $thumbs = array_filter($thumbs);
            $thumbs = array_unique($thumbs);

            if(!empty($video))
            {
                foreach($video as $item)
                {
                    $item = ltrim($item,'/');
                    @is_file($item) && @unlink($item);
                }
            }

            if(!empty($thumbs))
            {
                foreach($thumbs as $item)
                {
                    $item = ltrim($item,'/');
                    @is_file($item) && @unlink($item);
                }
            }

            $this->success('删除课程成功');
            exit;
        }
    }
}
